package alogrithm;

/**
 * @author lbw
 * @date 2021/10/16 10:59
 * @version 1.0
 */
public class GetLongestPalindrome {

    public int getLongestPalindrome(String A, int n) {
        // write code here
        // 中心扩展算法
        if (A.length() < 2) {
            return n;
        }
        int strat = 0, end = 0;
        for (int i = 0; i < n; ++i) {
            int len1 = expandAroundCenter(A, i, i);
            int len2 = expandAroundCenter(A, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - strat) {
                strat = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return end - strat - 1;
    }

    private int expandAroundCenter(String a, int left, int right) {
        while (left > 0 && right < a.length() && a.charAt(left) == a.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }
}
